package com.apps.sevents;

import com.apps.sconfig.SDevFastConfig;
import com.apps.sexctption.NullException;
import com.apps.sutils.StringUtils;
import com.apps.sworld.sWorld;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.SchedulingConfigurer;
import org.springframework.scheduling.config.ScheduledTaskRegistrar;
import org.springframework.scheduling.support.CronTrigger;

import java.util.List;

@Slf4j
@Configuration      //1.主要用于标记配置类，兼备Component的效果。
@EnableScheduling   // 2.开启定时任务
public class DynamicScheduleTask implements SchedulingConfigurer {

    @Autowired(required = false)
    private List<sWorld> worlds;

    @Autowired
    private SDevFastConfig devFastConfig;

    @Override
    public void configureTasks(ScheduledTaskRegistrar taskRegistrar) {

        if(devFastConfig.getHeartopen().intValue() == 0)
            return;
        taskRegistrar.addTriggerTask(
                //1.添加任务内容(Runnable)
                () -> heartbeat(),
                //2.设置执行周期(Trigger)
                triggerContext -> {
                    //2.2 合法性校验.
                    if (StringUtils.isEmpty(devFastConfig.getHeartCorn()))
                         throw new NullException("系统心跳周期参数为空");
                    //2.3 返回执行周期(Date)
                    return new CronTrigger(devFastConfig.getHeartCorn()).nextExecutionTime(triggerContext);
                }
        );
    }

    /**
     * 执行系统心跳
     */
    private void heartbeat()
    {
        if(null ==worlds)
            return;
        for(sWorld world:worlds)
            world.onHeart();
    }


}
